/*
 * Copyright 2011 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.paymentexpress.server.decrypt;

import org.keyczar.Crypter;
import org.keyczar.SignedSessionDecrypter;
import org.keyczar.Verifier;
import org.keyczar.exceptions.KeyczarException;

import com.google.paymentexpress.jwt.EncryptedData;

/**
 * Decryption class that uses the Keyczar library to decrypt
 * 
 * @author pying@google.com(peng ying)
 */
public class Decrypter {

  //TODO(pying): move these to tests
  //private final String testField = "AJhTpaEAAABJAEtIOzL1d1tmfl3d13rd15S67YcuuIlqnebBqxz_c4KxY2TxsGLtWwWpr4zOa2Zy3NF7aIvzIhGXUNVj4UMuFZdoskwy9KsYpTAsAhQeiYDvVwxOBS-jYsJQC9eS6dq8BgIUCbsPNkq_BwCU2J8GK855CnEY5_EAAAAAAAAA";
  //private final String testSession = "AMmCkmwoM6P3m5peXP027PItHRmg66YwYA7oduNQWoXWAmq8evera4_m24hGbMSRKJDWsYxBdKI9aMJr75dzoC2C-mNz-pAwJ090N7217SD1L3pK1XaUPoOY-XT7vjSCrMJ79QLFOmdTD55hM7zWxI_w8r4lUB-Q7op41xHihaRR79FsbH-7RKjoYwiM6BROyV8EOya-toF3Odg9UKO6q782vJyBHTKDyyLruRTAZTenyPCcGw1VC8yA6pbAosFlghIQSSVb0tM_WFO9l55jlreEPSLmDIoI4EzwmK34Fr1T1ZeQ2qEQrcvfNRYKWhxhfHleKyYZxYcK8iCXEIrlm3ko_q5h";
  
  private Crypter decrypter;
  private Verifier verifier;
  
  /**
   * Constructor
   */
  public Decrypter(){
  }
  
  public Decrypter(String rsaKeys, String dsaKeys){
    
  }
  
  public String decrypt(EncryptedData ed) throws KeyczarException{
    //TODO(pying): convert from content to JSON objects
    //TODO(pying): build out more functionality for this class
    
    //base64 decode to binary data
    byte[] fieldBytes = org.keyczar.util.Base64Coder.decode(ed.getField_data());
    
    String sessionData = ed.getSession_data();
    
    decrypter = new Crypter(new KeyczarHardCodedReader());
    verifier = new Verifier(new KeyczarHardCodedVerifier());
    SignedSessionDecrypter sessionDecrypter = new SignedSessionDecrypter(decrypter, verifier, sessionData);
    
    byte[] plainText = sessionDecrypter.decrypt(fieldBytes);
    
    return new String(plainText);
    
  }
}
